package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.BjExtraServiceInfo;
import com.taiyuan.tongcheng.bean.CargoPrice;
import com.taiyuan.tongcheng.bean.MovingOrderSimple;
import com.taiyuan.tongcheng.bean.MovingPrice;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.ACache;
import com.tytc56.user.R;


/**
 * 
* @Description 搬家物品选择界面
* @author wzq
* @date 2015-8-10 上午11:07:20
* @update (date)
* @version V1.0
 */

public class MovingListActivity extends BaseActivity implements OnGetRoutePlanResultListener{
	//家具选择布局
	@BindView(id=R.id.btn_furniture_add,click=true)
	private Button  furnitureBtnAdd;
	@BindView(id=R.id.etv_furniture)
	private EditText furnitureEtv;
	@BindView(id=R.id.btn_furniture_sub,click=true)
	private Button  furnitureBtnSub;
	//贵重物品选择布局
	@BindView(id=R.id.btn_precious_add,click=true)
	private Button   preciousBtnAdd;
	@BindView(id=R.id.etv_precious)
	private EditText preciousEtv;
	@BindView(id=R.id.btn_precious_sub,click=true)
	private Button   preciousBtnSub;
	//空调选择布局
	@BindView(id=R.id.btn_kongtiao_add,click=true)
	private Button  kongtiaoBtnAdd;
	@BindView(id=R.id.etv_kongtiao)
	private EditText kongtiaoEtv;
	@BindView(id=R.id.btn_kongtiao_sub,click=true)
	private Button  kongtiaoBtnSub;
	//家具美容选择布局
	@BindView(id=R.id.btn_meirong_add,click=true)
	private Button  meirongBtnAdd;
	@BindView(id=R.id.etv_meirong)
	private EditText meirongEtv;
	@BindView(id=R.id.btn_meirong_sub,click=true)
	private Button  meirongoBtnSub;
	//下一步
	@BindView(id=R.id.btn_next,click=true)
	private Button nextBtn;
	
	//==数据
	private MovingOrderSimple movingOrder;
	private int furnitureNum=0;
	private int preciousNum=0;
	private int kongtiaoNum=0;
	private int meirongNum=0;
	public static final int FURNITURE_KIND=5; //
	public static final int PRECIOUS_KIND=3;
	public static final int KONGTIAO_KIND=4;
	public static final int MEIRONG_KIND=6;
	public static final int MOVING_KIND=2;
	//搬家服务项
	private BjExtraServiceInfo furnitureInfo;
	private BjExtraServiceInfo preciousInfo;
	private BjExtraServiceInfo kongtiaoInfo;
	private BjExtraServiceInfo meirongInfo;
	private List<BjExtraServiceInfo> serviceList =new ArrayList<BjExtraServiceInfo>();
	
	//地图相关，路径规划
     RoutePlanSearch  routePlanSearch;
     private long disTance;//米数
     //intentFilter
     private IntentFilter intentFilter;
     
	@Override
	public void setRootView() {
		setContentView(R.layout.activity_moving_ui2);
	}
	
	@Override
	public void initData() {
		super.initData();
		movingOrder=(MovingOrderSimple)ACache.get(getApplicationContext()).getAsObject(MovingActivity.TAG_MOVING_ORDER);
		initBjExtraServiceInfo();
	}
	
	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		initReceiver();
		topTv.setText(R.string.lable_topbar_wupin);
		rightTv.setVisibility(View.GONE);
		//地图 
		routePlanSearch=RoutePlanSearch.newInstance();
		routePlanSearch.setOnGetRoutePlanResultListener(this);
	}
	
	/**
	 * 
	* @Description: 注册广播
	* @return void
	* @throws
	* @autour Administrator
	* @date 2015年9月19日 下午11:08:04 
	* @update (date)
	 */
    private void initReceiver() {
    	intentFilter=new IntentFilter();
    	intentFilter.addAction(TCBroadcastAction.SUCCESS_MAKE_ORDER);
    	registerReceiver(receiver, intentFilter);
	}
    
    private BroadcastReceiver  receiver =new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			MovingListActivity.this.finish();
		}
	};
	
	
	/**
	 * 
	* @Description: 初始化搬家服务
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-17 下午3:24:48
	* @update (date)
	 */
	private void initBjExtraServiceInfo() {
		furnitureInfo=new BjExtraServiceInfo();
		furnitureInfo.setBjExtraServiceId(FURNITURE_KIND);
		preciousInfo=new BjExtraServiceInfo();
		preciousInfo.setBjExtraServiceId(PRECIOUS_KIND);
		kongtiaoInfo=new BjExtraServiceInfo();
		kongtiaoInfo.setBjExtraServiceId(KONGTIAO_KIND);
		meirongInfo=new BjExtraServiceInfo();
		meirongInfo.setBjExtraServiceId(MEIRONG_KIND);
	}
	
	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.btn_furniture_add:
			addServiceNum(FURNITURE_KIND, furnitureEtv);
			break;
		case R.id.btn_furniture_sub:
			subServiceNum(FURNITURE_KIND, furnitureEtv);
			break;
		case R.id.btn_precious_add:
			addServiceNum(PRECIOUS_KIND, preciousEtv);
			break;
		case R.id.btn_precious_sub:
			subServiceNum(PRECIOUS_KIND, preciousEtv);
			break;
		case R.id.btn_kongtiao_add:
			addServiceNum(KONGTIAO_KIND, kongtiaoEtv);
			break;
		case R.id.btn_kongtiao_sub:
			subServiceNum(KONGTIAO_KIND, kongtiaoEtv);
			break;
		case R.id.btn_meirong_add:
			addServiceNum(MEIRONG_KIND, meirongEtv);
			break;
		case R.id.btn_meirong_sub:
			subServiceNum(MEIRONG_KIND, meirongEtv);
			break;
			
		case R.id.btn_next:
			
			//计算数量
			furnitureInfo.setNum(furnitureNum);
			preciousInfo.setNum(preciousNum);
			kongtiaoInfo.setNum(kongtiaoNum);
			meirongInfo.setNum(meirongNum);
			
			serviceList.add(furnitureInfo);
			serviceList.add(preciousInfo);
			serviceList.add(kongtiaoInfo);
			serviceList.add(meirongInfo);
			
			movingOrder.setExtraServiceInfo(getExtraServiceInfo());
			KJLoger.debug(getExtraServiceInfo());
			movingOrder.setExtraServiceInfoList(serviceList);
			ACache.get(getApplicationContext()).put(MovingActivity.TAG_MOVING_ORDER, movingOrder);
			getStationKm();
			KJLoger.debug(movingOrder.toString());
			TcLoaddingDialog.show();
			break;

		default:
			break;
		}
	}
	
	
	/**
	 * 
	* @Description: 获取数据
	* @return
	* @return String
	* @throws
	* @autour wzq
	* @date 2015-9-17 下午3:30:57
	* @update (date)
	 */
	private String getExtraServiceInfo() {
		return furnitureInfo.getServiceFomartString()+
				","+preciousInfo.getServiceFomartString()+
				","+kongtiaoInfo.getServiceFomartString()+
				","+meirongInfo.getServiceFomartString()
				;
	}
	
	/**
	 * 
	* @Description: 增加个类别的服务数量
	* @param serviceKind
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-17 下午3:32:38
	* @update (date)
	 */
	private void addServiceNum(int serviceKind,EditText kindServiceEtv) {
		switch (serviceKind) {
		case FURNITURE_KIND:
			furnitureNum++;
			kindServiceEtv.setText(furnitureNum+"");
			break;
		case PRECIOUS_KIND:
			preciousNum++;
			kindServiceEtv.setText(preciousNum+"");
			break;
		case KONGTIAO_KIND:
			kongtiaoNum++;
			kindServiceEtv.setText(kongtiaoNum+"");
			break;
		case MEIRONG_KIND:
			meirongNum++;
			kindServiceEtv.setText(meirongNum+"");
			break;

		default:
			break;
		}
       
	}
	/**
	 * 
	* @Description: 减少类别的服务数量
	* @param serviceKind
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-17 下午3:32:43
	* @update (date)
	 */
	private void subServiceNum(int serviceKind,EditText kindServiceEtv){
		switch (serviceKind) {
		case FURNITURE_KIND:
			if(furnitureNum>0){
				furnitureNum--;
			}
			kindServiceEtv.setText(furnitureNum+"");
			break;
		case PRECIOUS_KIND:
			if(preciousNum>0){
				preciousNum--;
			}
			kindServiceEtv.setText(preciousNum+"");
			break;
		case KONGTIAO_KIND:
			if(kongtiaoNum>0){
				kongtiaoNum--;
			}
			kindServiceEtv.setText(kongtiaoNum+"");
			break;
		case MEIRONG_KIND:
			if(meirongNum>0){
				meirongNum--;
			}
			kindServiceEtv.setText(meirongNum+"");
			break;

		default:
			break;
		}
	}
	/**
	 * 
	* @Description: 根据里程获取服务器价格
	* @return void
	* @throws
	* @autour wzq
	* @date 2015-9-18 上午10:44:58
	* @update (date)
	 */
	private void getMovingForecastPrice() {
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjHttp = new KJHttp(config);
		HttpParams httpPrams = HttpParamUtil.getMovingForecastPrice(
				getApplicationContext(), movingOrder);
		kjHttp.post(TcWebservice.WEBSERVER_IP
				+ TcWebservice.API.MOVING_GET_PRICE, httpPrams,
				new HttpCallBack() {
					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						try {
						String str;
						str = URLDecoder.decode(new String(t), "UTF-8");
						KJLoger.debug(str);
							WebData webData = TcJsParser.getWedataData(str);
							if (webData.getStatus() == 1) {
								MovingPrice  price=JSON.parseObject(
										webData.getData(), MovingPrice.class);
								ACache.get(getApplicationContext()).put(MovingActivity.TAG_MOVING_ORDER_PRICE, price);
								KJLoger.debug(price.toString());
								//=====================获取价格成功=================================
								if (TcLoaddingDialog.isShowing()) {
									TcLoaddingDialog.dismiss();
								}
								startActivity(MovingOrderMakeActivity.class);
							} else {
								showCustomToast(webData.getMsg());
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
						if (errorNo == -1) {
							// 网络超时
							ViewInject.toast(strMsg);
						}
					}
				});
	}
	
	
	/**
	 * 
	* @Description: 获取起点+路径点+
	* @return void
	* @throws
	* @autour Administrator
	* @date 2015-8-30 下午4:49:24 
	* @update (date)
	 */
	private void getStationKm() {
		PlanNode stNode = PlanNode.withLocation(new LatLng(movingOrder.getStartLatitude(), movingOrder.getStartLongitude()));  
		PlanNode enNode = PlanNode.withLocation(new LatLng(movingOrder.getEndLatitude(), movingOrder.getEndLongitude()));
        routePlanSearch.drivingSearch(new DrivingRoutePlanOption().from(stNode).to(enNode).policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_DIS_FIRST));
		//====20151116测试=======
//		 routePlanSearch.drivingSearch(new DrivingRoutePlanOption().from(stNode).to(enNode).policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_TIME_FIRST));
//        routePlanSearch.drivingSearch(new DrivingRoutePlanOption().from(stNode).to(enNode).policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_FEE_FIRST));
	}
	@Override
	public void onGetWalkingRouteResult(WalkingRouteResult result) {
		// 获取步行线路规划结果
	}

	@Override
	public void onGetTransitRouteResult(TransitRouteResult result) {
		// 获取公交换乘路径规划结果
	}

	@Override
	public void onGetDrivingRouteResult(DrivingRouteResult result) {
		
		if(result!=null){
			disTance=0;
			// 获取驾车线路规划结果
			List<DrivingRouteLine>  list = result.getRouteLines();
			for (int i = 0; i < list.size(); i++) {
				disTance+=list.get(i).getDistance();
			}
			movingOrder.setTotalMeter(disTance);
			double meter=Math.round(disTance/100d)/10d;
			movingOrder.setTotalKmNum(DoubleToInt(meter));
			//如果计大于0算得出的公里数
			if(movingOrder.getTotalKmNum()>0){
				getMovingForecastPrice();
			}
			KJLoger.debug("搬家前== "+meter+"=处理后="+DoubleToInt(meter));
//			ViewInject.toast("公里数"+movingOrder.getTotalKmNum());
			showErroCustomToast("公里数："+movingOrder.getTotalKmNum());
		}
	}
	
	
	/**
	 * 
	 * @param f
	 * @return 获取整数
	 */
	public int DoubleToInt(double f){
	    int i = 0;
	    if(f>0) //正数
	      i = (int)(f*10 + 10)/10;
	    return i;

	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(receiver);
	}
}
